const fs = require('fs');
const path = require('path');

//创建两个正则表达式用来匹配<style>和<script>
const regStyle = /<style[^>]*>([\s\S]*)<\/style>/ig;
const regScript = /<script[^>]*>([\s\S]*)<\/script>/ig;


//读取了index.html
fs.readFile(path.join(__dirname, './index.html'), 'utf8', function(err, dataStr) {
    if (err) {
        return console.log(err.message);
    }
    //匹配<style>和<script>
    const styleArr = regStyle.exec(dataStr);
    const scriptArr = regScript.exec(dataStr);
    // console.log(styleArr);
    // console.log(scriptArr);
    // console.log(styleArr[1]);
    // console.log(scriptArr[1]);
    // console.log(styleArr[0]);
    resolveCSS(styleArr[1]);
    resolveJS(scriptArr[1]);
    resolveHTML(dataStr, styleArr[0], scriptArr[0]);
});

//自定义resolveCSS方法，来写入index.css文件
function resolveCSS(dataStr) {
    fs.writeFile(path.join(__dirname, '../时钟小案例/clock/index.css'), dataStr, function(err) {
        if (err) {
            return console.log(err.message);
        }
        console.log('写入index.css成功');
    });
};

//自定义resolveJS方法，来写入index.js文件
function resolveJS(dataStr) {
    fs.writeFile(path.join(__dirname, '../时钟小案例/clock/index.js'), dataStr, function(err) {
        if (err) {
            return console.log(err.message);
        }
        console.log('写入index.js成功');
    });
};

//修改index.html文件，将<style>和<script>删除
function resolveHTML(dataStr, dataStyle, dataScript) {
    const stylePath = path.join('./index.css');
    const scriptPath = path.join('./index.js');
    const newStyleStr = `<link rel="stylesheet" href="${stylePath}">`;
    const newScriptStr = `<script src="${scriptPath}"></script>`;
    let newHTMLStr = dataStr.replace(dataStyle, newStyleStr).replace(dataScript, newScriptStr);
    fs.writeFile(path.join(__dirname, '../时钟小案例/clock/index.html'), newHTMLStr, function(err) {
        if (err) {
            return console.log(err.message);
        }
        console.log('写入index.html成功');
    });
};